package com.example.codeloginjava.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.codeloginjava.mode.WebSocketModel;
import com.example.codeloginjava.websocket.LoginWebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

// 我这边也不写 Service 了，直接在这里写完
@RestController
public class LoginController {

    @Autowired
    LoginWebSocketServer loginWebSocketServer;

    // 可以让前端直接通过 websocket 通知，也可以单独发送请求 让系统内部通知
    @CrossOrigin("*")
    @PostMapping("/api/login_code")
    public HashMap<String, Boolean> loginCode(@RequestBody JSONObject jsonObject) {
        String to = jsonObject.getString("to");
        boolean isCode = jsonObject.getBoolean("isCode");
        WebSocketModel<Map<String,Boolean>> webSocketModel = new WebSocketModel();
        HashMap<String, Boolean> m = new HashMap<>();
        m.put("isCode", isCode);
        webSocketModel.setCode(101);
        webSocketModel.setDate(new Date());
        webSocketModel.setData(m);
        webSocketModel.setMessage("success");
        TextMessage message = new TextMessage(JSONObject.toJSONString(webSocketModel));
        loginWebSocketServer.sendInfo(to, message);
        return m;
    }

    @CrossOrigin("*")
    @PostMapping("/api/login")
    public JSONObject login(@RequestBody JSONObject jsonObject) {
        String username = jsonObject.getString("username");
        String to = jsonObject.getString("to");
        String mode = jsonObject.getString("mode");
        JSONObject obj = new JSONObject();
        obj.put("username", username);
        obj.put("token", "ABCD");
        if("CODE".equals(mode)) {
            WebSocketModel<JSONObject> webSocketModel = new WebSocketModel();
            webSocketModel.setCode(101);
            webSocketModel.setDate(new Date());
            webSocketModel.setData(obj);
            webSocketModel.setMessage("success");
            TextMessage message = new TextMessage(JSONObject.toJSONString(webSocketModel));
            loginWebSocketServer.sendInfo(to, message);
        }

        return obj;
    }


}
